﻿param($computerNames,$collectionConfigurationFilePath,$startTime,$endTime,$exportPath)


$parentPath=(Split-Path $PSCommandPath -Parent)
$collectionConfiguration=Import-Csv -Delimiter "^" -Path $collectionConfigurationFilePath

$scriptBlock= 
    {
        param($providerName,$computerName,$startTime,$endTime,$exportPath,$excludedEventIds)
        Import-Module -Force -DisableNameChecking $using:parentPath\libWindowsEvent.psm1
        Import-Module -Force -DisableNameChecking $using:parentPath\..\BuildDeployment\libAssertion.psm1

        if($startTime -eq $null)
        {
            if(Test-Path -Path $exportPath\Tracking\$computerName`_$providerName.txt)
            {
                $startTime=Get-Content $exportPath\Tracking\$computerName`_$providerName.txt
            }
            else
            {
                $startTime=(Get-Date).Subtract([Timespan]::FromDays(1825)).ToString("yyyy-MM-dd")
            }
        }

        if($endTime -eq $null)
        {
            $endTime=(Get-Date).ToString("yyyy-MM-dd")
        }
        Assert-Directory -Path "$exportPath\$providerName"
        Assert-Directory -Path "$exportPath\Tracking"
        Get-ComputerEvent -providerName $providerName -computerName $computerName -startTime $startTime -endTime $endTime -excludedEventIds $excludedEventIds | Normalize-Event | Export-Csv -Path $exportPath\$providerName\$computerName.csv -Delimiter "^" -Append -NoTypeInformation
        $endTime | Set-Content -Path $exportPath\Tracking\$computerName`_$providerName.txt -Force
    }

foreach($computerName in $computerNames)
{
    
    foreach($collection in $collectionConfiguration)
    { 
        $jobName="Gather events from "+ $collection.ProviderName +" on $computerName"

        $jobStarted=$false

        while(-not $jobStarted)
        {
            $activeJobCount=(Get-Job -Name "Gather events*" | Where {$_.State -eq "Running"} | Measure-Object).Count
            if($activeJobCount -le 30)
            {
                Start-Job -Name $jobName -ScriptBlock $scriptBlock -ArgumentList $collection.ProviderName,$computerName,$startTime,$endTime,$exportPath,$collection.ExcludedEventIds
                $jobStarted=$true
            }
            else
            {
                Start-Sleep -Seconds 5
            }
        }
    }
}

do
{
    Get-Job "Gather events*" | Receive-Job
    Get-Job "Gather events*" | where {$_.State -eq "Completed"} | Remove-Job
    Start-Sleep -Seconds 15   
}
while(((Get-Job -Name "Gather events*" | Where {$_.State -eq "Running"} | Measure-Object).Count) -gt 0)

Remove-Item -Path $exportPath\CoreEvents.csv -Force -Confirm:$false

foreach($collection in $collectionConfiguration)
{
    $providerName=$collection.ProviderName
    Get-ChildItem $exportPath\$providerName\*.csv | ForEach-Object {Import-Csv -Delimiter "^"   $_} | Export-Csv -Delimiter "^" -NoTypeInformation $exportPath\CoreEvents.csv -Append
}
